package v1

import (
	"RoccBlog/api"
	"RoccBlog/global"
	"RoccBlog/model"
	v1 "RoccBlog/service/v1"
	"github.com/gin-gonic/gin"
	"strconv"
)

type RouterController struct {
	api.BaseController
	api.BaseOperationController
	Service *v1.RouterService
}

func init() {
	global.RegisterController(&RouterController{})
}

func (c *RouterController) RegisterController(engine *gin.RouterGroup) {
	// 配置server
	c.Service = global.GetService(v1.RouterService{}).(*v1.RouterService)

	g := engine.Group("/router")
	{
		g.POST("", c.Add)
		g.DELETE("", c.Remove)
		g.PUT("", c.Modify)
		g.GET("/list", c.Find)
		g.GET("", c.FindById)
	}
}

// Add
// @Tags 路由管理
// @Summary 添加路由
// @Produce  json
// @Param router body model.Router required "路由"
// @Success 200 {object} api.Result "成功"
// @Router /router [post]
func (c *RouterController) Add(ctx *gin.Context) {
	var router model.Router
	err := ctx.ShouldBind(&router)
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}

	err = c.Service.Add(ctx, router)
	c.HandleResponseNoResult(ctx, err, "创建路由失败", "创建路由成功！")
}

// Remove
// @Tags 路由管理
// @Summary 删除路由
// @Produce  json
// @Param id query int required "路由id"
// @Success 200 {object} api.Result "成功"
// @Router /router [delete]
func (c *RouterController) Remove(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Query("id"))
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}

	err = c.Service.Remove(ctx, id)
	c.HandleResponseNoResult(ctx, err, "删除路由失败", "删除路由成功！")
}

// Modify
// @Tags 路由管理
// @Summary 修改路由
// @Produce  json
// @Param router body model.Router required "路由"
// @Success 200 {object} api.Result "成功"
// @Router /router [put]
func (c *RouterController) Modify(ctx *gin.Context) {
	var router model.Router
	err := ctx.ShouldBind(&router)
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}

	err = c.Service.Modify(ctx, router)
	c.HandleResponseNoResult(ctx, err, "修改路由失败", "修改路由成功！")
}

// Find
// @Tags 路由管理
// @Summary 路由列表
// @Produce  json
// @Param pageNum query int false "页码"
// @Param pageSize query int false "每页数量"
// @Success 200 {object} api.Result "成功"
// @Router /router/list [get]
func (c *RouterController) Find(ctx *gin.Context) {

	pageInfo, err := c.Service.Find(ctx)
	c.HandleResponseResult(ctx, err, "获取路由列表失败", pageInfo)
}

// FindById
// @Tags 路由管理
// @Summary 路由列表
// @Produce  json
// @Param id query int false "路由id"
// @Success 200 {object} api.Result "成功"
// @Router /router [get]
func (c *RouterController) FindById(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Query("id"))
	if err != nil {
		c.ResponseBadRequest(ctx)
		return
	}
	router, err := c.Service.FindById(ctx, id)
	c.HandleResponseResult(ctx, err, "获取路由失败", router)
}
